package com.zw.yzk.kabu.presenter;

import android.support.v7.app.AppCompatActivity;

import com.qiniu.android.common.Zone;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.Configuration;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UploadManager;
import com.zw.yzk.kabu.R;
import com.zw.yzk.kabu.base.BaseSubscriber;
import com.zw.yzk.kabu.constant.ActivityConstant;
import com.zw.yzk.kabu.data.cache.db.DataBaseManager;
import com.zw.yzk.kabu.data.network.entity.HomePageEntity;
import com.zw.yzk.kabu.data.network.task.CollectTask;
import com.zw.yzk.kabu.data.network.task.DeleteCosTask;
import com.zw.yzk.kabu.data.network.task.FollowTask;
import com.zw.yzk.kabu.data.network.task.HomePageTask;
import com.zw.yzk.kabu.data.network.task.ModifyUserInfoTask;
import com.zw.yzk.kabu.data.network.task.PraiseTask;
import com.zw.yzk.kabu.data.network.task.Task;
import com.zw.yzk.kabu.domain.repository.UseCase;
import com.zw.yzk.kabu.management.LoadingDialogManager;
import com.zw.yzk.kabu.management.ToastManager;
import com.zw.yzk.kabu.mapper.HomePagerMapper;
import com.zw.yzk.kabu.view.view.HomepageView;

import org.json.JSONObject;

import java.util.UUID;

import javax.inject.Inject;
import javax.inject.Named;

/**
 * Created by zhanwei on 2017/3/4.
 */

public class HomePagePresenter implements Presenter {

    private UseCase getHomePage;
    private UseCase getUploadToken;
    private UseCase modifyUserInfo;
    private UseCase collectCosplay;
    private UseCase praiseCosplay;
    private UseCase deleteCosplay;
    private UseCase follow;
    private AppCompatActivity activity;
    private HomepageView homepageView;
    private HomePagerMapper mapper;
    private String uploadToken;
    private ModifyUserInfoTask task;
    private UploadManager uploadManager;

    @Inject
    public HomePagePresenter(@Named("homePageUseCase") UseCase getHomePage,
                             @Named("uploadImageTokenUseCase") UseCase getUploadToken,
                             @Named("modifyUserInfoUseCase") UseCase modifyUserInfo,
                             @Named("collectUseCase") UseCase collectCosplay,
                             @Named("praiseUseCase") UseCase praiseCosplay,
                             @Named("deleteCosUseCase") UseCase deleteCosplay,
                             @Named("followUseCase")UseCase follow,
                             AppCompatActivity activity, HomePagerMapper mapper) {
        this.getHomePage = getHomePage;
        this.getUploadToken = getUploadToken;
        this.modifyUserInfo = modifyUserInfo;
        this.collectCosplay = collectCosplay;
        this.praiseCosplay = praiseCosplay;
        this.deleteCosplay = deleteCosplay;
        this.follow = follow;
        this.activity = activity;
        this.mapper = mapper;
    }

    public void setHomepageView(HomepageView view) {
        this.homepageView = view;
    }

    public void follow(int publisherId, boolean concern) {
        follow.execute(new FollowSubscriber(activity), new FollowTask(publisherId, concern ? 1 : 0));
    }

    public void praise(int cosplayId, boolean praise) {
        praiseCosplay.execute(new PraiseCosplaySubscriber(activity), new PraiseTask(cosplayId, praise ? 1 : 0));
    }

    public void collect(int cosplayId, boolean collect) {
        collectCosplay.execute(new CollectCosplaySubscriber(activity), new CollectTask(cosplayId, collect ? 1 : 0));
    }

    public void delete(int cosplayId) {
        deleteCosplay.execute(new DeleteCosSubscriber(activity), new DeleteCosTask(cosplayId));
    }

    public void getHomePageInfo(int ownerId, String nickName, int start, int lastId) {
        HomePageTask task = new HomePageTask(ownerId, start, lastId);
        task.ownerName = nickName;
        getHomePage.execute(new GetHomePageSubscriber(activity), task);
    }

    public void getHomePageInfo(String ownerName, int start, int lastId) {
        getHomePage.execute(new GetHomePageSubscriber(activity), new HomePageTask(ownerName, start, lastId));
    }

    public void getUploadImageToken() {
        getUploadToken.execute(new GetUploadTokenSubscriber(activity), new Task());
    }

    public void modifyImage(String filePath, boolean isHead) {
        task = new ModifyUserInfoTask();
        task.nickName = null;
        task.sex = DataBaseManager.getInstance().getLoginUser().getSex();
        task.province = null;
        task.city = null;
        task.sign = null;

        //上传图片到七牛
        uploadToQiNiu(filePath, uploadToken, isHead);
    }

    private void uploadToQiNiu(String filePath, String token, final boolean isHead) {
        if (uploadManager == null) {
            uploadManager = new UploadManager(
                    new Configuration.Builder()
                            .build());
        }
        String expectKey = UUID.randomUUID().toString();
        uploadManager.put(filePath, expectKey, token, new UpCompletionHandler() {
            public void complete(String k, ResponseInfo info, JSONObject response) {
                if (info.isOK()) {
                    if(isHead) {
                        task.head = ActivityConstant.QINIU_PERFIX + response.optString("key");
                    } else {
                        task.homePage = ActivityConstant.QINIU_PERFIX + response.optString("key");
                    }

                    //修改头像
                    modifyUserInfo.execute(new ModifyUserInfoSubscriber(activity), task);
                } else {
                    LoadingDialogManager.getInstance().dismissLoadingDialog();
                    ToastManager.getInstance().showToast(activity, activity.getResources().getString(R.string.upload_image_failed));
                }
            }
        }, null);
    }

    @Override
    public void resume() {

    }

    @Override
    public void pause() {

    }

    @Override
    public void destroy() {
        getHomePage.unSubscribe();
        getUploadToken.unSubscribe();
        modifyUserInfo.unSubscribe();
        collectCosplay.unSubscribe();
        praiseCosplay.unSubscribe();
        deleteCosplay.unSubscribe();
        follow.unSubscribe();
    }

    private class FollowSubscriber extends BaseSubscriber<Boolean> {

        public FollowSubscriber(AppCompatActivity appCompatActivity) {
            super(appCompatActivity);
        }

        @Override
        public String addErrorMessage() {
            return null;
        }
    }

    private class GetHomePageSubscriber extends BaseSubscriber<HomePageEntity> {

        public GetHomePageSubscriber(AppCompatActivity appCompatActivity) {
            super(appCompatActivity);
        }

        @Override
        public void onNext(HomePageEntity homePageEntity) {
            super.onNext(homePageEntity);
            homepageView.setHeaderInfo(mapper.transferHeader(homePageEntity));
            homepageView.getCosplayListSuccess(mapper.transferCosList(homePageEntity));
        }

        @Override
        public void onError(Throwable e) {
            super.onError(e);
            homepageView.getCosplayListFail();
        }

        @Override
        public void onCompleted() {
            super.onCompleted();
            LoadingDialogManager.getInstance().dismissLoadingDialog();
        }

        @Override
        public String addErrorMessage() {
            return activity.getResources().getString(R.string.get_home_page_info_failed);
        }
    }

    private class GetUploadTokenSubscriber extends BaseSubscriber<String> {

        public GetUploadTokenSubscriber(AppCompatActivity appCompatActivity) {
            super(appCompatActivity);
        }

        @Override
        public void onNext(String s) {
            super.onNext(s);
            uploadToken = s;
        }

        @Override
        public String addErrorMessage() {
            return activity.getResources().getString(R.string.get_upload_image_token_failed);
        }
    }

    private class ModifyUserInfoSubscriber extends BaseSubscriber<Boolean> {

        public ModifyUserInfoSubscriber(AppCompatActivity appCompatActivity) {
            super(appCompatActivity);
        }

        @Override
        public String addErrorMessage() {
            return activity.getResources().getString(R.string.modify_user_info_failed);
        }

        @Override
        public void onNext(Boolean aBoolean) {
            super.onNext(aBoolean);
            homepageView.refreshHeadSuccess();
            ToastManager.getInstance().showToast(activity, activity.getResources().getString(R.string.modify_success));
        }

        @Override
        public void onCompleted() {
            super.onCompleted();
            LoadingDialogManager.getInstance().dismissLoadingDialog();
        }
    }

    private class CollectCosplaySubscriber extends BaseSubscriber<Boolean> {

        public CollectCosplaySubscriber(AppCompatActivity appCompatActivity) {
            super(appCompatActivity);
        }

        @Override
        public String addErrorMessage() {
            return "";
        }

    }

    private class PraiseCosplaySubscriber extends BaseSubscriber<Boolean> {

        public PraiseCosplaySubscriber(AppCompatActivity appCompatActivity) {
            super(appCompatActivity);
        }

        @Override
        public String addErrorMessage() {
            return "";
        }
    }

    private class DeleteCosSubscriber extends BaseSubscriber<Boolean> {

        public DeleteCosSubscriber(AppCompatActivity appCompatActivity) {
            super(appCompatActivity);
        }

        @Override
        public String addErrorMessage() {
            return "";
        }
    }
}
